//
//  OutlineLabel.swift
//  描边的文字显示
//
//  Created by 千策万划-mini on 2025/4/29.
//

import Foundation

class OutlineLabel: UIView {
    
    var text: String = ""
    
    // MARK: - lazy
    lazy var labelTitle: UILabel = {
        let result = UILabel()
        return result
    }()
    
    // MARK: - init
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.widthHeight = XY(0, 0)
        self.isUserInteractionEnabled = false
        self.backgroundColor = .clear
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 重置界面
    func resetView(
        title: String = "",
        textColor: UIColor = COLOR_WHITE(),
        font: UIFont = UIFont.customBoldFont(size: 20),
        shadowColor: UIColor = .clear,
        outlineColor: UIColor = .clear,
        strokeColor: String = "",
        widthMark: CGFloat = 0.0
    ) {
        text = title
        labelTitle.textColor = textColor
        labelTitle.font = font
        labelTitle.fitTitle(title, variable: widthMark > 0 ? widthMark : 0)
        self.widthHeight = XY(labelTitle.width+6, labelTitle.height+6)
        labelTitle.centerXCenterY = XY(width/2, height/2)
        
        // 添加阴影
        labelTitle.shadowColor = shadowColor
        labelTitle.shadowOffset = CGSize(width: 0, height: 2)
        
        // 创建背景标签（只显示描边）
        let strokeLabel = UILabel()
        strokeLabel.frame = labelTitle.frame
        strokeLabel.font = labelTitle.font
        strokeLabel.textAlignment = labelTitle.textAlignment
        let strokeAttributes: [NSAttributedString.Key: Any] = [
            .strokeColor: outlineColor,
            .strokeWidth: 6,  // 正值表示只有描边
            .foregroundColor: UIColor.clear
        ]
        strokeLabel.attributedText = NSAttributedString(string: widthMark > 0 ? getDisplayedText(label: labelTitle) : title, attributes: strokeAttributes)

        let bgLabel = UILabel()
        bgLabel.widthHeight = XY(strokeLabel.width+6, strokeLabel.height+6)
        bgLabel.font = labelTitle.font
        bgLabel.textAlignment = .center
        let bgAttributes: [NSAttributedString.Key: Any] = [
            .strokeColor: isStr(strokeColor) ? UIColor(hex: strokeColor) : .clear,
            .strokeWidth: 29,      // 负值会同时显示描边和填充
            .foregroundColor: isStr(strokeColor) ? UIColor(hex: strokeColor) : .clear  // 填充色也设置为橙色
        ]
        bgLabel.attributedText = NSAttributedString(string: widthMark > 0 ? getDisplayedText(label: labelTitle) : title, attributes: bgAttributes)
        bgLabel.centerXCenterY = XY(strokeLabel.centerX, strokeLabel.centerY+0.6)
        
        self.removeAllSubviews()
        // 确保正确的层级关系
        self.addSubview(bgLabel)     // 最底层：背景
        self.addSubview(strokeLabel) // 中间层：描边
        self.addSubview(labelTitle)  // 最顶层：文字
    }
    
    // 导航栏 演示
    func resetNavTitle(title: String = "") {
        resetView(title: title,
                  textColor: COLOR_WHITE(),
                  font: UIFont.customBoldFont(size: 20),
                  shadowColor: UIColor(hex: "#2D0084"),
                  outlineColor: UIColor(hex: "#2D0084"),
                  strokeColor: "#F78D0F"
        )
    }
    
    func getDisplayedText(label: UILabel) -> String {
        guard let text = label.text, let font = label.font else { return "" }
        let labelWidth = label.bounds.width
        let ellipsis = "…"
        let displayedText = text

        // 先判断是否需要省略
        let attributes: [NSAttributedString.Key: Any] = [.font: font]
        let fullWidth = (text as NSString).boundingRect(
            with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: label.bounds.height),
            options: .usesLineFragmentOrigin,
            attributes: attributes,
            context: nil
        ).width

        if fullWidth <= labelWidth {
            return text // 没有省略
        }

        // 需要省略，逐步截断
        for i in 0..<text.count {
            let subText = (text as NSString).substring(to: i) + ellipsis
            let subWidth = (subText as NSString).boundingRect(
                with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: label.bounds.height),
                options: .usesLineFragmentOrigin,
                attributes: attributes,
                context: nil
            ).width
            if subWidth > labelWidth {
                // 上一个就是能显示的最大内容
                let lastSubText = (text as NSString).substring(to: max(0, i-1)) + ellipsis
                return lastSubText
            }
        }
        return displayedText
    }
}
